package com.kye.express.business.notice.notice_detail;

import android.content.Context;
import android.content.Intent;
import android.databinding.DataBindingUtil;
import android.os.Bundle;
import android.support.v7.app.ActionBar;
import android.support.v7.widget.LinearLayoutManager;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.PopupWindow;

import com.jakewharton.rxbinding2.view.RxView;
import com.kennyc.bottomsheet.BottomSheet;
import com.kye.base.DebounceObservableTransformer;
import com.kye.base.Logger;
import com.kye.base.utils.GsonUtils;
import com.kye.express.R;
import com.kye.express.business.base.BaseAppCompatActivity;
import com.kye.express.business.notice.notice_detail.viewbinder.NoticeDetailBasicInfoViewBinder;
import com.kye.express.databinding.ActivityNoticeDetailBinding;
import com.kye.express.databinding.BottomSheetCommentInputBinding;
import com.kye.express.utils.ScreenUtils;
import com.kye.express.view.NotificationCommentBottomSheet;
import com.kye.express.view.NotificationCommentDialog;
import com.kye.express.view.ToastManager;
import com.kye.lib.view.statuslayout.StatusLayout;
import com.kye.model.base.BaseItem;
import com.kye.model.bean.notice.NotificationDetailBasicInfoBean;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadmoreListener;

import net.yslibrary.android.keyboardvisibilityevent.KeyboardVisibilityEvent;
import net.yslibrary.android.keyboardvisibilityevent.KeyboardVisibilityEventListener;
import net.yslibrary.android.keyboardvisibilityevent.Unregistrar;

import java.util.ArrayList;
import java.util.List;

import io.reactivex.functions.Consumer;
import me.drakeet.multitype.MultiTypeAdapter;

public class NoticeDetailActivity extends BaseAppCompatActivity implements NoticeDetailContract.NoticeDetailView {
    private static final String TAG_NOTIFICATION_ID = "TAG_NOTIFICATION_ID";
    private long notificationId;
    protected ActivityNoticeDetailBinding mDataBinding;
    protected NoticeDetailContract.NoticeDetailPresenter mPresenter;
    protected MultiTypeAdapter mAdapter;
    protected List<BaseItem> dataList = new ArrayList<>();
    protected Unregistrar keyboardRegister;
    private NotificationCommentBottomSheet notificationCommentBottomSheet;
    private NotificationCommentDialog notificationCommentDialog;

    public static Intent newIntent(Context context, long notificationId) {
        Intent intent = new Intent(context, NoticeDetailActivity.class);
        intent.putExtra(TAG_NOTIFICATION_ID, notificationId);
        return intent;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (savedInstanceState == null) {
            notificationId = getIntent().getLongExtra(TAG_NOTIFICATION_ID, 0);
        } else {
            notificationId = savedInstanceState.getLong(TAG_NOTIFICATION_ID, 0);
        }
        mDataBinding = DataBindingUtil.setContentView(this, R.layout.activity_notice_detail);
        mPresenter = new NoticeDetailContract.NoticeDetailPresenter();
        mPresenter.onCreate(savedInstanceState);
        mPresenter.bind(this);
        initToolbar();
        initViews(savedInstanceState);
        initEvents(savedInstanceState);
        initData(savedInstanceState);
    }

    private void initToolbar() {
        setSupportActionBar(mDataBinding.toolbar);
        ActionBar actionBar = getSupportActionBar();
        if (actionBar != null) {
            actionBar.setDisplayHomeAsUpEnabled(true);
            actionBar.setTitle("通知详情");
        }
        mDataBinding.toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
    }

    private void initViews(Bundle savedInstanceState) {
        mAdapter = new MultiTypeAdapter();
        mAdapter.register(NotificationDetailBasicInfoBean.class, new NoticeDetailBasicInfoViewBinder());
        mAdapter.setItems(dataList);
        mDataBinding.refreshLayout.setEnableLoadmore(false);
        mDataBinding.rvNoticeDetails.setLayoutManager(new LinearLayoutManager(this));
        mDataBinding.rvNoticeDetails.setAdapter(mAdapter);
    }

    private void initEvents(Bundle savedInstanceState) {

        keyboardRegister = KeyboardVisibilityEvent.registerEventListener(
                this,
                new KeyboardVisibilityEventListener() {
                    @Override
                    public void onVisibilityChanged(boolean isOpen) {
                        if (!isOpen) {

                        }
                    }
                });
        mDataBinding.refreshLayout.setOnRefreshLoadmoreListener(new OnRefreshLoadmoreListener() {
            @Override
            public void onLoadmore(RefreshLayout refreshlayout) {
                // todo : 加载评论
            }

            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                mPresenter.getNotificationDetailInfo(notificationId);
            }
        });
        mDataBinding.statusLayout.setOnLoadingListener(new StatusLayout.OnLoadingListener() {
            @Override
            public void onLoading() {
                mPresenter.getNotificationDetailInfo(notificationId);
            }
        });
        RxView.clicks(mDataBinding.llErrorNet.btErrorNetRetry)
                .compose(this.bindToLifecycleDestroy())
                .compose(new DebounceObservableTransformer<Object>())
                .subscribe(new Consumer<Object>() {
                    @Override
                    public void accept(Object o) throws Exception {
                        mDataBinding.statusLayout.showLoadingView();
                    }
                });
        RxView.clicks(mDataBinding.llErrorServer.btErrorServerRetry)
                .compose(this.bindToLifecycleDestroy())
                .compose(new DebounceObservableTransformer<Object>())
                .subscribe(new Consumer<Object>() {
                    @Override
                    public void accept(Object o) throws Exception {
                        mDataBinding.statusLayout.showLoadingView();
                    }
                });
        RxView.clicks(mDataBinding.comment)
                .compose(this.bindToLifecycleDestroy())
                .compose(new DebounceObservableTransformer<Object>())
                .subscribe(new Consumer<Object>() {
                    @Override
                    public void accept(Object o) throws Exception {
                        showBottomSheetComment();
                    }
                });
    }

    private void initData(Bundle savedInstanceState) {
        mDataBinding.statusLayout.showLoadingView();
    }

    @Override
    public void getNotificationDetailInfoSuccess(NotificationDetailBasicInfoBean notificationDetailBasicInfoBean) {
        Logger.d("getNotificationDetailInfoSuccess\n" + GsonUtils.toJsonString(notificationDetailBasicInfoBean, true));
        if (!mPresenter.isInitRefresh()) {
            mDataBinding.refreshLayout.finishRefresh(true);
        }
        mDataBinding.statusLayout.showContentView();
        dataList.clear();
        dataList.add(notificationDetailBasicInfoBean);
        mAdapter.setItems(dataList);
        mAdapter.notifyDataSetChanged();
    }

    @Override
    public void getNotificationDetailInfoFailed(Throwable e) {
        if (!mPresenter.isInitRefresh()) {
            mDataBinding.refreshLayout.finishRefresh(false);
        }
        mDataBinding.statusLayout.showErrorServerView();
        ToastManager.show(this, e.getMessage());
    }

    @Deprecated
    @Override
    public void showBottomSheetCommentInput() {
        LayoutInflater layoutInflater = LayoutInflater.from(this);
        final BottomSheetCommentInputBinding binding = DataBindingUtil.inflate(layoutInflater, R.layout.bottom_sheet_comment_input, null, false);
        final BottomSheet bottomSheet = new BottomSheet.Builder(this)
                .setView(binding.getRoot()).create();
        bottomSheet.show();
        RxView.clicks(binding.commentSend)
                .compose(this.bindToLifecycle())
                .compose(new DebounceObservableTransformer<Object>())
                .subscribe(new Consumer<Object>() {
                    @Override
                    public void accept(Object o) throws Exception {
                        String comment = binding.commentInputText.getText().toString();
                        Logger.d("comment : " + comment);
                    }
                });
    }

    public void showBottomSheetComment() {
        if (notificationCommentBottomSheet == null) {
            notificationCommentBottomSheet = new NotificationCommentBottomSheet(this);
            notificationCommentBottomSheet.setClickListener(new NotificationCommentBottomSheet.OnClickListener() {
                @Override
                public void onSend(String comment) {
                    Logger.d("send : " + comment);
                }
            });
            notificationCommentBottomSheet.setOnDismissListener(new PopupWindow.OnDismissListener() {
                @Override
                public void onDismiss() {
                    ScreenUtils.resetBackgroundDefaultAlph(NoticeDetailActivity.this);
                }
            });
        }
        if (!notificationCommentBottomSheet.isShowing()) {
            ScreenUtils.setBackgroundDefaultAlph(this);
            notificationCommentBottomSheet.showAtLocation(mDataBinding.container, Gravity.BOTTOM, 0, 0);
        }
//        if (notificationCommentDialog == null) {
//            notificationCommentDialog = NotificationCommentDialog.newInstance();
//        }
//        DialogUtils.show(notificationCommentDialog, getSupportFragmentManager(), NotificationCommentDialog.class.getSimpleName());
    }

    public void dimissBottomSheetComment() {
        if (notificationCommentBottomSheet != null && notificationCommentBottomSheet.isShowing()) {
            notificationCommentBottomSheet.dismiss();
        }
//        DialogUtils.dimiss(notificationCommentDialog);
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        outState.putLong(TAG_NOTIFICATION_ID, notificationId);
        mPresenter.onSaveInstanceState(outState);
        super.onSaveInstanceState(outState);
    }

    @Override
    protected void onStart() {
        super.onStart();
    }

    @Override
    protected void onStop() {
        super.onStop();

    }

    @Override
    protected void onDestroy() {
        mPresenter.unbind();
        keyboardRegister.unregister();
        super.onDestroy();
    }

    @Override
    public ActivityNoticeDetailBinding getDataBinding() {
        return mDataBinding;
    }

    @Override
    public long getNotificationId() {
        return notificationId;
    }
}
